var express = require("express");
var router = express.Router();



 let {studentModel} = require("../models/studentModel") //导入学生模型


// 获取所有学生以及班级信息
router.get("/GetAllStudents_class", async (req, res, next) => {
    let result = await studentModel.find().populate('classId');
    if (result) {
      res.send({
        code: 200,
        obj: result,
      });
    }
  });


/*获取所有学生 */
router.get("/GetAllStudents", async (req, res, next) => {
  let result = await studentModel.find(req.query); //有值为精确查询，没值为全部查询
  if (result) {
    res.send({
      code: 200,
      obj: result,
    });
  }
});
/*增加学生 */
router.post("/addAllStudents", async (req, res, next) => {
  let arr = await studentModel.find({ sid: req.body.sid });
  if (arr.length < 1) {
    //如果里面有之前存入的sid,查找的数据长度会是个空数组，然后再添加
    studentModel.create(req.body);
    let new_arr = await studentModel.find();
    res.send({
      result: new_arr,
      code: 200,
    });
  } else {
    res.send({
      result: "添加失败",
      code: 201,
    });
  }

});

/*删除学生 */
router.post("/deleteStudents", async (req, res, next) => {

  let { deletedCount } = await studentModel.deleteOne(req.body);
  if (deletedCount == 1) {
    let new_arr = await studentModel.find().populate('classId');
    res.send({
      result: new_arr,
      code: 200,
    });
  } else {
    res.send({
      result: "删除失败",
      code: 201,
    });
  }
});

//修改学生信息
router.post("/updateStudent", async (req, res) => {
  let { matchedCount } = await studentModel.updateOne(
    { sid: req.body.sid },
    {
      sname: req.body.sname,
      gender: req.body.gender,
      telephone: req.body.telephone,
      age: req.body.age,
    }
  );
  if (matchedCount == 1) {
    res.send({
      code: 200,
      message: "修改成功",
    });
  } else {
    res.send({
      code: 200,
      message: "修改不成功",
    });
  }
});

//模糊查询学生信息
router.post("/findStudent_name", async (req, res) => {
  let result = await studentModel.find({ sname: { $regex: req.body.sname } });
  if (result.length > 0) {
    res.send({
      message: result,
      code: 200,
    });
  } else {
    res.send({
      message: "无数据",
      code: 201,
    });
  }
});


//分页且模糊查询学生信息
router.post("/page", async (req, res) => {
   let show_num = req.body.show_num
   let start_num = (req.body.page_num -1) * req.body.show_num
  //skip为从第几条数据开始查,limit里面为从展示几个
  let result = await studentModel.find({sname:{$regex:req.body.sname}}).skip(start_num).limit(parseInt(show_num))
  let result_count = await studentModel.countDocuments({sname:{$regex:req.body.sname}}) //里面不写值为所有的数据的个数，写值则也会模糊查询一次
  res.send({
     data:{
         rows:result,
         count:result_count
     },

      code:200
  })

  });
  
let {uploadImages} = require('../controls/studentsMethoded')
//上传图片
router.post('/uploadImages',uploadImages)


module.exports = router;
